import React, { useContext, useEffect, useRef, useState } from 'react';
import axios from "axios";
import { Button, Form, Input, Popconfirm, Table } from 'antd';
import { DeleteOutlined} from "@ant-design/icons";
export default function Category() {
  const [dataSource, setDataSource] = useState([]);
  useEffect(() => {
    const getDataSource = async () => {
      const res = await axios.get("http://localhost:3000/categories");
      setDataSource(res.data);
    };
    getDataSource();
  }, []);
  const handleSave = (record) => {
    setDataSource(dataSource.map(item=>{
      if(item.id===record.id){
         return {
           id:item.id,
           title:record.title,
           value:record.title,
         }
      }
      return item;
    }))
    axios.patch(`http://localhost:3000/categories/${record.id}`,{title:record.title,value:record.title})
  }
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    { 
      title: "新闻分类",
      dataIndex: "value",
      key: "value",
      onCell: record => ({
        record,
        editable: true,
        dataIndex:'title',
        title:'新闻分类',
        handleSave,
      }),
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <>
            <Popconfirm
              title="确定删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                confirmDelete(item);
              }}
            >
              <Button icon={<DeleteOutlined />} shape="circle" danger></Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];
  
  const confirmDelete=(item)=>{
    setDataSource(dataSource.filter((data) => data.id !== item.id))
    axios.delete(`http://localhost:3000/categories/${item.id}`)
  }

  const EditableRow = ({...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
  const EditableContext = React.createContext(null);
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current?.focus();
      }
    }, [editing]);
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };
    let childNode = children;
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{ margin: 0 }}
          name={dataIndex}
          rules={[{ required: true, message: `${title} is required.` }]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{ paddingInlineEnd: 24 }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
    return <td {...restProps}>{childNode}</td>;
  };
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5,
        }}
        components={components}
        rowKey={(item) => item.id}
      />
    </div>
  );
}
